<?php
/**
 * Created by PhpStorm.
 * User: 12297
 * Date: 2018/5/23
 * Time: 1:34
 */
namespace app\api\service;

use app\common\BaseHelper;
use app\common\DictConstant;
use app\common\model\Groupdetail;
use app\common\model\Orderproductdetail;
use app\common\model\Refundorder;
use app\common\model\Store;
use app\common\model\Useraccountdetails;
use app\common\service\TemplateMessage;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;
use think\Loader;
use think\Log;

Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');

/**
 * 团购失败批量退款
 * Class GroupRefund
 * @package app\api\service
 */
class GroupRefund{


    public function grouprefund($groupListFail){
        foreach ($groupListFail as $value){
            $store = Store::get($value->storeId);
            $tenant = \app\admin\model\Tenant::get($store->tenantId);
            if($tenant->certfile && $tenant->certkey){
                $this->refund($value);
            }
        }
    }

    private function refund($value){
        Db::startTrans();
        try{
            $order = \app\common\model\Order::get($value->orderId);
            $orderpro = Orderproductdetail::where(['orderId'=>$value->orderId,'productId'=>$value->groupproduct->productId])->find();
            $this->checkorder($order,$orderpro);
            $refund = new Refundorder();
            $thisrefund = $refund->where(['orderNO'=>$order->orderNO,'status'=>4])->find();
            if($thisrefund){
                $data =  [
                    'orderNO' => $order->orderNO,
                    'productId' => $thisrefund->productId,
                    'payMethod' => $order->payMethod,
                    'out_refund_no' => $thisrefund->out_refund_no,
                    'tenantId' => $order->tenantId,
                    'create_time' => $thisrefund->create_time,
                    'group_hours' => $value->groupproduct->groupDateStr,
                    'group_nums' => $value->groupproduct->groupSuccCount
                ];

                $this->doRefund($data);
                Db::commit();
                return true;

            }
            $out_refund_no = Order::makeOrderNo();
            $refund->id = BaseHelper::getUUID();
            $refund->orderNO = $order->orderNO;
            $refund->orderProductDetailId = $orderpro->id;
            $refund->productId = $value->groupproduct->productId;
            $refund->count = $order->total_count;
            $refund->storeId = $order->storeId;
            $refund->tenantId = $order->tenantId;
            $refund->userId = $order->createUser;
            $refund->out_refund_no = $out_refund_no;
            $refund->transaction_Id = $order->transaction_Id;
            $refund->refund_fee = $order->total;
            $refund->actualrefund_fee = $order->total;
            $refund->oldTotal = $order->total;
            $refund->save();
            $order->status = DictConstant::Order_Reefund;
            $order->save();
            //return show(1,'ok',$orderpro);
            Db::commit();
            $data =  [
                'orderNO' => $order->orderNO,
                'productId' => $refund->productId,
                'payMethod' => $order->payMethod,
                'out_refund_no' => $out_refund_no,
                'tenantId' => $order->tenantId,
                'create_time' => $refund->create_time,
                'group_hours' => $value->groupproduct->groupDateStr,
                'group_nums' => $value->groupproduct->groupSuccCount
            ];
            $this->doRefund($data);
        }catch (Exception $ex){
            Db::rollback();
            throw $ex;
        }

    }

    private function doRefund($data){
        $refundorder = Refundorder::where(['orderNO'=>$data['orderNO'],'productId'=>$data['productId']])->find();
        if(!$refundorder){
            throw new ParameterException([
                'msg' => '该售后订单不存在'
            ]);
        }
        if($data['payMethod'] == 0){
            //微信支付
            $this->ActiveRefund($refundorder->out_refund_no,$data['tenantId']);
        }else{
            //账户余额支付
            $this->BalanceRefund($refundorder->out_refund_no,$data['orderNO'],$data['group_hours'],$data['group_nums']);
        }

    }

    private function BalanceRefund($out_refund_no,$orderNO,$group_hours,$group_nums){
        Db::startTrans();
        try{
            $refundorder = Refundorder::where(['out_refund_no'=>$out_refund_no])->find();
            $endDate = date('Y-m-d H:i:s',time());
            $refundorder->endDate = $endDate;
            $refundorder->status = 2;
            $refundorder->reason = '拼团失败，自动退款';
            $refundorder->save();
            $order = \app\common\model\Order::where('orderNO','=',$orderNO)->find();
            $orderId = $order->id;
            $order->status = DictConstant::Order_Agree;
            $order->save();
            $Groupdetail = Groupdetail::where('orderId',$orderId)->find();
            $Groupdetail->status = 3;
            $Groupdetail->save();
            //返还用户余额
            \app\common\model\User::where('id',$order->createUser)->setInc('balance',$refundorder->refund_fee);

            //写入消费记录
            $Useraccountdetails = new Useraccountdetails();
            $Useraccountdetails->insertRecord($refundorder,Useraccountdetails::TYPE_2,Useraccountdetails::MODEL_2);
            Db::commit();
            //发送模板消息
            TemplateMessage::refundsendmessage($orderId,$group_hours,$group_nums);
        }catch (Exception $ex){
            Db::rollback();
            throw $ex;
        }



    }


    private function ActiveRefund($out_refund_no,$tenantId){
        $refundorder = Refundorder::where(['out_refund_no'=>$out_refund_no])->find();
        $wxRefundData = new \WxPayRefund();
        $wxRefundData->SetTotal_fee(intval($refundorder->oldTotal));
        $wxRefundData->SetOut_trade_no($refundorder->orderNO);
        $wxRefundData->SetOut_refund_no($out_refund_no);
        $wxRefundData->SetRefund_fee(intval($refundorder->refund_fee));
        return $this->WxRefund($wxRefundData,$tenantId);

    }

    private function WxRefund($wxRefundData,$tenantId){
        $wxRefund = \WxPayApi::grouprefund($wxRefundData,$tenantId);
        if($wxRefund['return_code'] != 'SUCCESS' || $wxRefund['result_code'] != 'SUCCESS'){
            Log::record($wxRefund,'error');
            Log::record('微信退款失败','error');
            dump('微信退款失败');
        }else{
            //微信退款成功后的处理逻辑
            $this->WxRefundSuccess($wxRefund);

        }
    }
    private function WxRefundSuccess($wxRefund){
        Db::startTrans();
        try{
            $mch_id = $wxRefund['mch_id'];
            $refund_id = $wxRefund['refund_id'];
            $endDate = date('Y-m-d H:i:s',time());
            $refundorder = Refundorder::where('out_refund_no','=',$wxRefund['out_refund_no'])->find();
            $refundorder->refund_id = $refund_id;
            $refundorder->op_user_id = $mch_id;
            $refundorder->endDate = $endDate;
            $refundorder->reason = '拼团失败，自动退款';
            $refundorder->status = 2;
            $refundorder->save();
            $order = \app\common\model\Order::where('orderNO','=',$wxRefund['out_trade_no'])->find();
            $orderId = $order->id;
            $order->status = DictConstant::Order_Agree;
            $order->save();
            $Groupdetail = Groupdetail::where('orderId',$orderId)->find();
            $Groupdetail->status = 3;
            $Groupdetail->save();
            //写入消费记录
            $Useraccountdetails = new Useraccountdetails();
            $Useraccountdetails->insertRecord($refundorder,Useraccountdetails::TYPE_7,Useraccountdetails::MODEL_2);
            Db::commit();
        }catch (Exception $ex){
            Db::rollback();
            throw $ex;
        }
    }


    private function checkorder($order,$orderpro){
        if(!$order){
            throw new ParameterException([
                'msg' => '该订单不存在'
            ]);
        }
        if(!$orderpro){
            throw new ParameterException([
                'msg' => '该订单商品不存在'
            ]);
        }
//        if($order->status!=2 && $order->status!=8){   //status = 3 已经发货订单 用户与商家协商自行处理
//            throw new ParameterException([
//                'msg' => '该订单不能售后666'
//            ]);
//        }
        if($orderpro->oldStatus != 2 && $orderpro->oldStatus != 8 && $orderpro->oldStatus != 9){
            throw new ParameterException([
                'msg' => '此商品不能进行售后了'
            ]);
        }
    }
}